﻿using DBUtility;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Utilities;
using WeChat.Models;

namespace WeChat.Controllers
{
    public class DingController : Controller
    {
        DbHelper helper = new DbHelper("3");
        log4net.ILog logger = log4net.LogManager.GetLogger("WeChatConnect");
        string AgentID = "183699523";
   
        //企业接口调用CorpSecret
        string CorpId = "dinge658fc251884befe35c2f4657eb6378f";
        string CorpSecret = "1nt9xITEZd5RD1LHC-Nw0RBej6CIIgbDIT_npQqULbL5AXsDw77KGj3HaTYGkakw";

        //微应用管理后台SSOSecret
        //string SSOSecret = "HFv3dATkJiEoO_7eo_ShJ7rpSAY897_RZy5Iwv5z00GNNDNrBm-bF06Vj-TNEEbV";

        ////服务窗应用ChannelSecret
        //string ChannelSecret = "8JPWq8Vx6-CV3ZJxnazdEbIxUI73u1BuWwdxf3BmUKf-4vJOE_k3TZ_6YfXKq2iE";

        // GET: Ding
        public ActionResult Index()
        {
            logger.Debug("进入主方法Index:");
            BeginDDAutoLogin();
            logger.Debug("结束主方法Index:");
            return View();
        }

        public  ActionResult GetUserInfo(string accessToken, string code, bool setCurrentUser = true)
        {
            try
            {
                logger.Debug("进入主方法Index:");
                string userId = DDApiService.Instance.GetUserId(accessToken, code);
                string jsonString = DDApiService.Instance.GetUserDetailJson(accessToken, userId);
                UserDetailInfo userInfo = DDApiService.Instance.GetUserDetailFromJson(jsonString);
                if (setCurrentUser)
                {
                    Session["AccessToken"] = accessToken;
                    Session["CurrentUser"] = userInfo;
                }
                return Content(jsonString);
            }
            catch (Exception ex)
            {
                return Content(string.Format("{{'errcode': -1, 'errmsg':'{0}'}}", ex.Message));
            }
        }

        public ActionResult GetList(string userId)
        {
            string isBindingSql = string.Format(@"select top 5 * from groupuser where  wechat='{0}'", userId);
            var query = helper.GetDataSet(isBindingSql);
            UserInfo model = new UserInfo();
            List<UserInfo> list = new List<UserInfo>();
            if (query.Tables[0].Rows.Count > 0)
            {


                //persons.Add(new UserInfo() { Email = "email" + i, Name = "name", IsMarried = false, PhoneNum = "1234" + i, Home = CityEnum.BJ, Height = i });
       
                //return Json(persons, JsonRequestBehavior.AllowGet);

                list = IListDataSet.ToList<UserInfo>(query.Tables[0]);
            }
            //return Content(model.ToJson());
            return Json(list, JsonRequestBehavior.AllowGet);
        }


        public ActionResult Test()
        {
            return View();
        }

        public ActionResult Login()
        {
            BeginDDAutoLogin();
            return View();
        }

        private void BeginDDAutoLogin()
        {
            string nonceStr = "helloDD" + System.DateTime.Now.ToString();//todo:随机
            ViewBag.NonceStr = nonceStr;
            string accessToken = DDApiService.Instance.GetAccessToken();
            logger.Debug("获取accessToken:" + accessToken);
            ViewBag.AccessToken = accessToken;
            string ticket = DDApiService.Instance.GetJsApiTicket(accessToken);
            logger.Debug("获取ticket:" + ticket);
            long timeStamp = DDHelper.GetTimeStamp();
            string url = Request.Url.ToString();
            string signature = DDApiService.Instance.GetSign(ticket, nonceStr, timeStamp, url);

            ViewBag.JsApiTicket = ticket;
            ViewBag.Signature = signature;
            ViewBag.NonceStr = nonceStr;
            ViewBag.TimeStamp = timeStamp;
            ViewBag.CorpId = DDApiService.Instance.CorpId;
            ViewBag.CorpSecret = DDApiService.Instance.CorpSecret;
            ViewBag.AgentId = DDApiService.Instance.AgentId;
        }
    }
}